import { Component, Emit, Prop, Watch } from 'vue-facing-decorator'
import Render from '@/render/Render'
import toNative from '@/utils/toNative'
import renderModal, { getModelValue, initModelValue, renderForm, type FormModalDto } from '@/components/modal/Modal'
import { updatePayManagerUser } from '@/api/pay'
import type { FilterDto } from '@/render/FilterRender'
import {
    OpenAccountTypeCnEnum,
    OpenAccountTypeEnum,
    getKeyToEnum,
    ProductTypeEnum
} from '@/const/enum'

import { createAlipayRegisterUrl, setAlipayAccount, unSignAlipay } from '@/api/alipay'
import { addContact, editContact } from '@/api/deal'
import type { SaleReqDto } from '@/api/deal/types'
import type { CompanyInfoDto, PayWageInfoDto } from '@/api/company/types'
import { updateSaasCompany } from '@/api/company'
import { confirm, getReceiptData, goBack } from '@/utils/util'
import { Button, Image, message, Tag } from 'ant-design-vue'
import dayjs from 'dayjs'
import CustomTitle from '@/components/custom-title/Index'
import SuccessComponent from './SuccessComponent'
import type { OpenPayWageReqDto } from '@/api/product/types'
import { openPaywage } from '@/api/product'
// import { SuccessComponent } from './SuccessComponent'

@Component({
    expose: ['getData']
})
export class OpenPaywage extends Render {
    @Prop() basicData!: PayWageInfoDto
    @Prop() companyBasicInfo!: CompanyInfoDto

    showRecharge = false

    isSuccess = false

    @Emit('refresh')
    handleRefresh() {}

    @Watch('basicData')
    async handleWatch() {
        if (this.basicData.channelId) {
            this.basicFormConfig.items.receiptId.options = await getReceiptData(
                this.basicData.channelId
            )
        }
        this.basicData.openAccountType = []
        if (this.basicData.isOpenWechatPay) {
            this.basicData.openAccountType.push(OpenAccountTypeEnum.WECHAT)
            this.openFormConfig.items.subMchid.hidden = false
        }
        if (this.basicData.isOpenAlipay) {
            this.basicData.openAccountType.push(OpenAccountTypeEnum.ALIPAY)
            this.openFormConfig.items.alipay.hidden = false
        }
        // 根据支付宝账户时候绑定 显示对应按钮
        this.openFormConfig.items.alipay.params.prefix = this.basicData.isOpenAlipay ? (
            <Button ghost type="primary" onClick={this.onUnbindAuth}>
                解除授权
            </Button>
        ) : (
            <Button ghost type="primary" onClick={this.onCreateSignUrl}>
                生成签约码
            </Button>
        )
        initModelValue(this.basicFormConfig, Object.assign(this.basicData, this.companyBasicInfo))
        if (this.basicData.isOpenPaySalary) {
            initModelValue(this.openFormConfig, Object.assign(this.basicData, this.companyBasicInfo))
        }
    }

    basicFormConfig = this.initFormConfig() as FormModalDto
    initFormConfig() {
        return {
            title: '',
            width: '400px',
            theme: 'light',
            show: false,
            items: {
                saleId: {
                    name: '所属销售',
                    element: 'select',
                    optionsType: 'saleList',
                    required: true,
                    callback: {
                        change: async (value: number) => {
                            console.log(33333, value)
                        }
                    }
                },
                channelId: {
                    name: '收款渠道',
                    element: 'select',
                    optionsType: 'channel',
                    required: true,
                    callback: {
                        change: async (value: number) => {
                            this.basicFormConfig.items.receiptId.value = ''
                            if (value) {
                                this.basicFormConfig.items.receiptId.options =
                                    await getReceiptData(value)
                            } else {
                                this.basicFormConfig.items.receiptId.options = []
                            }
                        }
                    }
                },
                receiptId: {
                    name: '收款账号',
                    element: 'select',
                    required: true,
                    params: {
                        defaultAttrs: {
                            label: 'bankName',
                            value: 'id'
                        }
                    }
                },
                dailyQuota: {
                    name: '单日额度',
                    element: 'input'
                },
                personSingleQuota: {
                    name: '可领额度',
                    element: 'input'
                }
            },
            complete: async () => {
                const data = getModelValue(this.basicFormConfig)
                await updatePayManagerUser(data)
                message.success('更新成功')
                this.basicFormConfig.show = false
            },
            cancel: () => {
                this.basicFormConfig.show = false
            },
            init: () => {}
        } as FormModalDto
    }
    basicForm = {
        validate: async () => {},
        clear: () => {},
        element: () => <></>
    }

    openFormConfig = this.initOpenFormConfig() as FormModalDto
    initOpenFormConfig() {
        return {
            title: '',
            width: '400px',
            theme: 'light',
            show: false,
            items: {
                openAccountType: {
                    name: '开通账户',
                    element: 'checkboxGroup',
                    required: true,
                    options: getKeyToEnum(OpenAccountTypeCnEnum),
                    callback: {
                        change: (val: number[]) => {
                            this.openFormConfig.items.subMchid.hidden = !val.includes(
                                OpenAccountTypeEnum.WECHAT
                            )
                            this.openFormConfig.items.alipay.hidden = !val.includes(
                                OpenAccountTypeEnum.ALIPAY
                            )
                        }
                    }
                },
                subMchid: {
                    name: '微信商户号',
                    element: 'input',
                    required: true,
                    hidden: true
                },
                alipay: {
                    name: '企业支付宝认证',
                    element: 'text',
                    hidden: true,
                    params: {
                        prefix: <></>
                    }
                }
            },
            complete: async () => {
                const data = getModelValue(this.openFormConfig)
                await updatePayManagerUser(data)
                message.success('更新成功')
                this.openFormConfig.show = false
            },
            cancel: () => {
                this.openFormConfig.show = false
            },
            init: () => {}
        } as FormModalDto
    }
    openForm = {
        validate: async () => {},
        clear: () => {},
        element: () => <> </>
    }

    // 生成签约码
    async onCreateSignUrl() {
        const res = await createAlipayRegisterUrl({
            companyId: this.basicData.companyId
        })
        window.open(res)
    }
    
    // 解绑支付宝签约
    async onUnbindAuth() {
        await confirm('确定解约吗？', '提示', {
            okText: '确定',
            cancelText: '取消'
        })
        await unSignAlipay({
            companyId: this.basicData.companyId
        })
        this.handleRefresh()
    }
    

    filterBtnConfig() {
        return {} as FilterDto
    }

    async onSubmit(isOpenSalary: boolean) {
        this.basicForm.validate()
        this.openForm.validate()
        const basicFormData = getModelValue(this.basicFormConfig)
        const openFormData = getModelValue(this.openFormConfig)
        const { saleId, ...otherData } = basicFormData
        const params = {
            ...otherData,
        } as OpenPayWageReqDto
        params.id = this.basicData.companyId
        params.subMchid = openFormData.subMchid
        params.isOpenPaySalary = 1
        params.isOpenWechatPay = Number(openFormData.openAccountType.includes(OpenAccountTypeEnum.WECHAT))
        params.isOpenAlipay = Number(openFormData.openAccountType.includes(OpenAccountTypeEnum.ALIPAY))

        const saleParams = {
            companyId: this.basicData.companyId,
            id: this.basicData.dealId,
            productType: ProductTypeEnum.PAYWAGE,
            saleId: basicFormData.saleId,
            serviceStartTime: dayjs().startOf('day').format('YYYY-MM-DD'),
            serviceState: 0
        } as SaleReqDto
        // 未开通过支付宝账户，但勾选了开通
        if (!this.basicData.isOpenAlipay && params.isOpenAlipay) {
            await setAlipayAccount({
                companyId: this.basicData.companyId
            })
        }
        // 更新基本信息
        await openPaywage(params)
        // 更新销售人员  销售保存要在基本信息保存完之后执行
        if (!this.basicData.saleId) {
            await addContact(saleParams)
        } else {
            await editContact({
                ...saleParams,
                saleOldId: this.basicData.saleId
            })
        }
        message.success('更新成功')
        this.isSuccess = true
        // this.handleRefresh()
    }

    created() {
        this.basicForm = renderForm(this.basicFormConfig)
        this.openForm = renderForm(this.openFormConfig)
    }

    renderStatistics() {
        return <></>
    }

    renderRightBtns() {
        return <></>
    }

    render() {
        return this.isSuccess ? (
            <div class="h-full flex justify-center items-center">
                <SuccessComponent hint="已成功开通了发薪专户产品，需要继续添加方案，可在保险客户中心添加" />
            </div>
        ) :
            <div class="flex flex-col h-full">
                <div class="flex-1">
                    <CustomTitle>基本信息</CustomTitle>
                    <div class="mt-20px">{this.basicForm.element()}</div>
                    <CustomTitle>开通产品</CustomTitle>
                    <div class="mt-20px">{this.openForm.element()}</div>
                </div>
                <div class="pt-19px flex justify-center gap-20px">
                    <Button onClick={goBack}>取消</Button>
                    <Button type="primary" onClick={() => this.onSubmit(false)}>确认</Button>
                </div>
            </div>
    }
}

export default toNative<
    { basicData: PayWageInfoDto; companyBasicInfo?: CompanyInfoDto },
    { refresh: () => void }
        >(OpenPaywage)
